package com.cloudbroker.openapi.mobile.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * Created by wangxu13798 on 2016/3/11.
 */
@SuppressWarnings("deprecation")
public class YunxinUtil {
	public static final String APP_KEY = "69df5f35edf067919a20da5c03f648e6";
	public static final String APP_SECRET = "a04251cfc0e7";
	public static final String NONCE = "12345";

    public static String doPost(String url, Map<String, String> params) {
		@SuppressWarnings("resource")
        DefaultHttpClient httpClient = new DefaultHttpClient();

		try {
			List<NameValuePair> pairs = null;
			if (params != null && !params.isEmpty()) {
				pairs = new ArrayList<NameValuePair>(params.size());
				for (Map.Entry<String, String> entry : params.entrySet()) {
					String value = entry.getValue();
					if (value != null) {
						pairs.add(new BasicNameValuePair(entry.getKey(), value));
					}
				}
			}

			HttpPost httpPost = new HttpPost(url);
			String curTime = String.valueOf((new Date()).getTime() / 1000L);
			String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE,
					curTime);// 参考 计算CheckSum的java代码
			// 设置请求的header
			httpPost.addHeader("AppKey", APP_KEY);
			httpPost.addHeader("Nonce", NONCE);
			httpPost.addHeader("CurTime", curTime);
			httpPost.addHeader("CheckSum", checkSum);
			httpPost.addHeader("Content-Type",
					"application/x-www-form-urlencoded;charset=utf-8");
			// 设置请求的参数
			httpPost.setEntity(new UrlEncodedFormEntity(pairs, "utf-8"));
			// 执行请求
			HttpResponse response = httpClient.execute(httpPost);

			// 打印执行结果
			return EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
